<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <CommentDropdown v-model="postForm.comment_disabled" />
        <PlatformDropdown v-model="postForm.platforms" />
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          Publish
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          Draft
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="Name">
              <MDinput v-model="postForm.CoachName" :maxlength="100" name="CoachName" required>
                CoachName
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="5">
                  <el-form-item label="头像">
                    <div @click="imagecropperShow=true">
                      <pan-thumb :image="image" />

                      <image-cropper
                        v-show="imagecropperShow"
                        :key="imagecropperKey"
                        :width="300"
                        :height="300"
                        :url="url"
                        lang-type="en"
                        @close="close"
                        @crop-upload-success="cropSuccess"
                      />
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label="启用">
                    <el-switch v-model="postForm.Enable" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item label="个人经历">
          <el-input v-model="postForm.Experience" type="textarea" :autosize="{ minRows: 4}" />
        </el-form-item>
        <el-form-item label="带队经历">
          <el-input v-model="postForm.LeadTeam" type="textarea" :autosize="{ minRows: 4}" />
        </el-form-item>
        <el-form-item label="教育履历">
          <el-input v-model="postForm.Education" type="textarea" :autosize="{ minRows: 4}" />
        </el-form-item>

        <el-button type="text" @click="doRequestGetInfo">手动上传图片</el-button>

        <el-form-item>
          <el-upload
            action=""
            :auto-upload="false"
            list-type="picture-card"
            :file-list="pics"
            :on-preview="handlePictureCardPreview"
            :on-change="handleOnChange"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

<!--        <el-form-item prop="AvatarUrl" style="margin-bottom: 30px;">
          <Upload v-model="postForm.AvatarUrl" />
        </el-form-item> -->
      </div>
    </el-form>

  </div>
</template>

<script>
import axios from 'axios'
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import { fetchArticle } from '@/api/article'
import { searchUser } from '@/api/remote-search'

const defaultForm = {
  status: 'draft',
  CoachCode: '', // 教练编码
  CoachName: '', // 教练姓名
  AvatarUrl: '', // 头像
  Experience: '', // 个人经历
  LeadTeam: '', // 带队经历
  Education: '', // 教育履历
  Enable: true,
  display_time: undefined, // 前台展示时间
  id: undefined,
  platforms: ['a-platform'],
  comment_disabled: false
}

export default {
  name: 'MPCPDetail',
  components: { MDinput, Upload, Sticky, CommentDropdown, PlatformDropdown, ImageCropper, PanThumb },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        image_uri: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      imagecropperShow: false,
      imagecropperKey: 0,
      image: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
      url:'http://localhost:8099/wapi/UpdateHomeImages?userCode=test',
      pics: [],
      dialogImageUrl: '',
      dialogVisible: false,
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return (+new Date(this.postForm.display_time))
      },
      set(val) {
        this.postForm.display_time = new Date(val)
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    handleOnChange(file,fileList){
      this.pics.push(file)
    },
    doRequestGetInfo(){
      // axios.get('http://localhost:8099/wapi/getTestData').then(res=>{
      //   console.log(res)
      // }).catch(err=>{
      //   console.log(err)
      // });

      console.log(this.pics)

      if(this.pics.length>0){
        var fmData = new FormData();
        var file = this.pics[0];
        fmData.append('file', file.raw, file.name);
        console.log('file', fmData.get('file'));

        axios({
          method: "post",
          headers: {"Content-Type": "multipart/form-data"},
          url: "http://localhost:8099/wapi/UpdateHomeImages?userCode=test",
          data: fmData,
        }).then(resData => {
            if (resData.status == 200) {
              console.log(resData);
            }
        }).catch(err=> {
          console.log(err);
        });
      }

      // axios({
      //   method: "post",
      //   headers: {"Content-Type": "multipart/form-data"},
      //   url: "http://localhost:8099/wapi/UpdateHomeImages?userCode=test",
      //   data: fmData,
      // }).then(resData => {
      //     if (resData.status == 200) {
      //       console.log(resData);
      //       this.loading = 2
      //       this.$emit('crop-upload-success', resData.data.data)
      //     }
      // }).catch(err=> {
      //   console.log(err);
      //   this.loading = 3
      //   this.hasError = true
      //   this.errorMsg = lang.fail
      //   this.$emit('crop-upload-fail', err, field, ki)
      // });
    },
    handelClick(){
      this.imagecropperShow=true
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      console.log('handlePictureCardPreview',file.url)
      this.dialogVisible = true;
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log('handleAvatarSuccess',this.imageUrl,file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    cropSuccess(resData) {
      console.log('----------------------cropSuccess----------------------',resData)
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.image = 'http://localhost:8099/Images/HomeImages/' + resData
    },
    close() {
      this.imagecropperShow = false
    },
    fetchData(id) {
      fetchArticle(id).then(response => {
        this.postForm = response.data

        // just for test
        this.postForm.title += `   Article Id:${this.postForm.id}`
        this.postForm.content_short += `   Article Id:${this.postForm.id}`

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$notify({
            title: '成功',
            message: '发布文章成功',
            type: 'success',
            duration: 2000
          })
          this.postForm.status = 'published'
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map(v => v.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

// .avatar{
//   width: 200px;
//   height: 200px;
//   border-radius: 50%;
// }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
